dfs and similar dp dsu graphs *1400

Please click on ads to support us..

Python Code:

def dfs(start,end,color):
    global cond
    if cond:return
    visited.add(start)
    for child in nodes[start]:
        if cond : return
        if child==end:
            if color in pair[(min(child,start),max(child,start))]:
                cond=True ; return
        else:
            if child not in visited and color in pair[(min(child,start),max(child,start))]:
                dfs(child,end,color)
    if cond : return
    

n,m=map(int,input().split())  ; nodes=dict() ; pair=dict() ; colors=dict()
for i in range(m):
    x,y,c=map(int,input().split())
    if x not in nodes:  nodes[x]={y}
    else:               nodes[x].add(y)
    
    if y not in nodes:  nodes[y]={x}
    else:               nodes[y].add(x)
    
    if (x,y) in pair:   pair[(x,y)].append(c)
    else:               pair[(x,y)]=[c]
    
    if x in colors:     colors[x].add(c)
    else:               colors[x]={c}
    
    if y in colors:     colors[y].add(c)
    else:               colors[y]={c}


for i in range(int(input())):
    n1,n2=map(int,input().split()) ; ans=0 
    if n1 in colors.keys() and n2 in colors.keys():
        for j in colors[n1].intersection(colors[n2]):
            visited=set() ; cond=False
            dfs(n1,n2,j)
            if cond:ans+=1
    print(ans)
        
    

C++ Code:

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef unsigned long long ull;
#define fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
template <typename T>
using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;
#define of(m) find_by_order((m)); //random access of ordered set
#define all(v) (v).begin(),(v).end()
#define r_all(v) (v).rbegin(),(v).rend()
#define s(v) (v).size()
#define endl "\n";
#define NO cout << "NO\n";
#define YES cout << "YES\n";
#define No cout << "No\n";
#define Yes cout << "Yes\n";
#define PF push_front
#define PB push_back
#define MP make_pair
#define F first
#define S second

const int MOD = 1e9 + 7;
const int N = 1e6 + 5;


void print_vec(vector<ll>& v){
    for(ll i=0; i<s(v); i++) cout << v[i] << " ";
    cout << endl
}
bool is_sorted(vector<ll>& v){
    bool x = true;
    for(ll i=0; i<s(v)-1; i++) x &= (v[i] <= v[i+1]);
    return x;
}
bool is_palindrome_s(string s) {
    string p = s;
    reverse(all(p));
    if (s == p) return true;
    else return false;
}
bool is_palindrome_n(ll n) {
    ll temp = n, sum =0 ,r;
    while(n>0)
    {
        r=n%10;
        sum = (sum*10)+r;
        n/=10;
    }
    if (temp == sum) return true;
    else return false;
}


//Graph
const int M = 100+5;
bool vis[M];
vector<ll> adj[M];
vector<pair<ll,ll>> g[M];

void dfs(ll u){
    vis[u] = 1;
    for(ll v: adj[u]){
        if(!vis[v]) dfs(v);
    }
}
ll no_of_components_of_graph(ll n){
    ll cnt = 0;
    for(ll i=1; i<=n; i++){
        if(!vis[i]){
            dfs(i);
            cnt++;
        }
    }
    return cnt;
}
//The shortest path from a single source in a unweighted, directed graph
ll bfs_shortest_path(ll source, ll destination){
    queue<ll> q;
    q.push(source);
    vis[source] = 1;
    ll level = 0;
    for(;q.size(); ++level){
        for(ll sz = q.size();sz--;){
            ll u = q.front(); q.pop();
            if(u == destination) { return level; }
            for(ll v: adj[u]){
                if(!vis[v]){
                    q.push(v);
                    vis[v] =1;
                }
            }
        }
    }
    return -1;
}
ll bfs(ll u, ll m, ll color){
    queue<ll> q;
    q.push(u); vis[u] = 1;
    while(q.size()){
        ll sz = q.size();
        while(sz--){
            ll node = q.front(); q.pop();
            if(node == m) { return 1; }
            for(auto x: g[node]){
                if((x.S == color) && (!vis[x.F])){
                    q.push(x.F);
                    vis[x.F] = 1;
                    //cout << x.F <<endl
                }
            }
        }
    }
    return 0;
}


int main() {
    fast
    ll n, m; cin >> n >> m;
    set<ll> s;
    while(m--){
        ll u, v, color; cin >> u >> v >> color;
        s.insert(color);
        g[u].PB({v,color});
        g[v].PB({u,color});
    }
    ll q; cin >> q;
    while(q--){
        ll cnt = 0, l, r; cin >> l >> r;
        for(auto d: s){
            cnt += bfs(l, r, d);
            memset(vis, 0, sizeof vis);
        }
        cout << cnt << endl
    }
}


Comments

Submit
0 Comments
More Questions

1451A - Subtract or Divide
1B - Spreadsheet
1177A - Digits Sequence (Easy Edition)
1579A - Casimir's String Solitaire
287B - Pipeline
510A - Fox And Snake
1520B - Ordinary Numbers
1624A - Plus One on the Subset
350A - TL
1487A - Arena
1520D - Same Differences
376A - Lever
1305A - Kuroni and the Gifts
1609A - Divide and Multiply
149B - Martian Clock
205A - Little Elephant and Rozdil
1609B - William the Vigilant
978B - File Name
1426B - Symmetric Matrix
732B - Cormen --- The Best Friend Of a Man
1369A - FashionabLee
1474B - Different Divisors
1632B - Roof Construction
388A - Fox and Box Accumulation
451A - Game With Sticks
768A - Oath of the Night's Watch
156C - Cipher
545D - Queue
459B - Pashmak and Flowers
1538A - Stone Game